//
//  XTComposeVC.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/20.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit
import SVProgressHUD

class XTComposeVC: UIViewController ,UITextViewDelegate{

        //  MARK: -懒加载控件-
    //右侧的按钮
    private lazy var rightBtn :UIButton = {
        let btn = UIButton()
        //添加监听事件
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named:"common_button_orange" ), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Selected)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.size = CGSize(width: 45, height: 30)
        
        return btn
    }()
    
    
    //中间的两行的标题
    private lazy var titleLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fronSize: 17)
        if let name = XTUserAccountViewModel.sharedUserAccount.userAccount?.name{
        
            let titleText = "发微博\n\(name)"
            
            //获取name在字符串种的位置
            let range = (titleText as NSString).rangeOfString(name)
            //根据titleText创建富文本 ******富文本：即可以设置各种属性的文本
            let attributedStr = NSMutableAttributedString(string: titleText)
            
            //根据范围设置name的颜色和字体
                //Foreground：突出显示
            attributedStr.addAttribute(NSForegroundColorAttributeName,value:UIColor.lightGrayColor(),range:range)
            attributedStr.addAttribute(NSFontAttributeName,value:UIFont.systemFontOfSize(15),range:range)
            
            label.attributedText = attributedStr
            
        }else{
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
    
    }()
    
    
    //自定义的textView
    private lazy var textView:XTComposeTextView = {
    
        let textView = XTComposeTextView()
//        textView.placeHolder = "能不能显示" //可以实现
        //此处设置代理是为了监听textview是否有内容，然后决定发送按钮是否能点击
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
        //垂直方向可以滚动
        textView.alwaysBounceVertical = true
        
        return textView
    
    }()
    
    //自定义的底部toolBar
    private lazy var toolBar:XTComposeToolBar = {
        let view = XTComposeToolBar(frame:CGRectZero)
        return view
    }()
    
    
    //自定义的图片展示view
    private lazy var pictureView:XTComposePictureView = {
        let view = XTComposePictureView()
        
        return view
    
    }()
    
    //表情键盘
    private lazy var emoticonKeyBoard:XTEmoticonKeyBoard = {
        let keyBoard = XTEmoticonKeyBoard()
        keyBoard.size = CGSize(width: self.textView.width, height: 216)
        return keyBoard
    
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //监听键盘frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听点击表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticonBtn:", name: didSelectedEmoticonBtnNotification, object: nil)
        //监听到点击删除按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticonBtn", name: didSelectedDeleteEmoticonBtnNotification, object: nil)
        
        setupUI()
       
    }
    
    

    private func setupUI(){
    view.backgroundColor = UIColor.whiteColor()
    
        //添加子视图
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)//＊＊＊＊＊＊这里需要改
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        //接受toolBar返回的闭包并进行判断
        toolBar.didSelectedComposeToolBarBtnClosure = {[weak self] (type:ComposeToolBarBtnType) in
        
            switch type {
                case .Picture:
                    print("Picture")
                    self?.didSelectedPicture()
                case .Mention:
                    print("Mention")
                case .Trend:
                    print("Trend")
                case .Emoticon:
                    print("Emoticon")
                    self?.didSelectedEmoticon()
                case .Add:
                    print("Add")
                
            }
        }
        
        pictureView.didSelectedAddImageClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        setupNavUI()
    }

    //设置nav的UI界面
    private func setupNavUI(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        
        //右侧按钮     *******注意此处将自定义的按钮加进去的方法是通过customView！！！！！
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
            //右侧按钮默认为不可点击的
        navigationItem.rightBarButtonItem?.enabled = false
    
        navigationItem.titleView = titleLabel
    }
        //  MARK: -点击事件-
    @objc private func cancelAction(){
    
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送微博
    @objc private func sendAction(){
        
        if pictureView.imageArray.count > 0{
            //带图片的微博
            upload()
        }else{
            update()
        }
    }
    
    //发送带图片微博的请求
    private func upload(){
        //准备参数
        let access_token = XTUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emoticonText
        
        //发送“发布带图片微博”请求
        SVProgressHUD.show()
        XTNetWorkTools.sharedTools.upload(access_token, status: status, pic: pictureView.imageArray.first!) { (response, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }else{
                SVProgressHUD.showSuccessWithStatus("微博发布成功")
            }
        }
    
    }
    //发送纯文字微博的请求
    private func update(){
        //准备参数
        let access_token = XTUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emoticonText
        
        //发送“发布微博”请求
        
        SVProgressHUD.show()//此处若没有show方法，则在返回数据前没有任何提示；若有，则先显示转圈的等待，接收到返回数据后变成发送成功提示
        
        XTNetWorkTools.sharedTools.update(access_token, status: status) { (response, error) -> () in
            
            
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("微博发布成功")
        }

    }
    
        //  MARK: -textView的代理方法（用于查看textView是否有内容）-
    func textViewDidChange(textView: UITextView) {
        rightBtn.enabled = textView.hasText()
    }
    
    
        //  MARK: -监听键盘的frame变化-
    @objc private func keyBoardChangeFrame(noti:NSNotification){
//        print("----------")
//        print(noti.userInfo)
        // [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        
        //UIKeyboardAnimationCurveUserInfoKey为键盘消失和出现时动画的类型
        //UIKeyboardIsLocalUserInfoKey 表示键盘是展示还是隐藏状态：1，展示；0，隐藏
        
        var dic = noti.userInfo
        //获取键盘frame发生变化后最后的frame
        let endFrame = (dic!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        //获取键盘完成动画所需的时间
        let animationDuration = (dic!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
        
        //给toolBar更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(endFrame.origin.y - view.frame.size.height)
        }
        //刷新子控件布局所需的时间
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //点击表情按钮的通知的实现方法
    @objc private func didSelectedEmoticonBtn(noti:NSNotification){
        
        guard let emoticon = noti.object as? XTEmoticon else{
            return
        }
        //向textView上插入富文本
        textView.insertEmoticon(emoticon,font:textView.font!)
    }
    
    //    *********scrollViewDidScroll方法只要一滚动就调用，稍微一动会调用很多次，因此不使用该方法实现让键盘回收的效果
//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        self.view.endEditing(true)
//        print("scrollViewDidScroll")
//    }
    
    //在将要滚动前，也是scrollViewDidScroll前执行一次
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    deinit{
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

    //  MARK: -点击按钮的扩展方法-
    //UIImagePickerController比较特殊，需要实现两个代理协议，除了自身的还有UINavigationController的
extension XTComposeVC:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //点击表情按钮的方法
    private func didSelectedEmoticon(){
        if textView.inputView == nil{
            //没有表情键盘时
            textView.inputView = emoticonKeyBoard
            toolBar.showEmoticonIcon(true)
        
        }else{
            textView.inputView = nil
            toolBar.showEmoticonIcon(false)
        }
        //textView变为第一响应者
        textView.becomeFirstResponder()
        //刷新inputView
        textView.reloadInputViews()
        
    }
    
    //点击图片按钮的方法
    private func didSelectedPicture(){
        
        let imgPicker = UIImagePickerController()
        imgPicker.delegate = self
        //判断是启用相机还是进入相册
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            //若支持相机则开启相机
            imgPicker.sourceType = .Camera
        }else if(UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)){
            imgPicker.sourceType = .PhotoLibrary
        }
        
        //判断使用前置摄像头还是后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front){
            print("前置摄像头可用")
        }else if(UIImagePickerController.isCameraDeviceAvailable(.Rear)){
            print("后置摄像头可用")
        }else{
            print("摄像头不可用")
        }
        
        presentViewController(imgPicker, animated: true, completion: nil)
    }
    
    //监听到表情键盘删除按钮被点击时的调用的事件
    @objc private func didSelectedDeleteEmoticonBtn(){
        textView.deleteBackward()
    }
    
    
    
        //  MARK: -UIImagePickerController的代理方法-
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        pictureView.addImage(image)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //??????????该方法直接不写效果就一致呗？？？？是的
    
//    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
//        picker.dismissViewControllerAnimated(true, completion: nil)
//    }

}
